package com.tanklab.signature.service.impl;

import com.tanklab.signature.service.FileStorageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Service
public class FileStorageServiceImpl implements FileStorageService {
    @Value("${avatar.upload-dir}")
    private String uploadDir;

    @Value("${avatar.access-path}")
    private String accessPath;

    @Override
    public String storeAvatar(MultipartFile file) throws IOException {
        // 验证文件是否为空
        if (file.isEmpty()) {
            throw new IOException("无法保存空文件");
        }

        // 获取原始文件名，并确保它是安全的
        String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());

        // 防止意外的".."进入文件路径
        if (originalFilename.contains("..")) {
            throw new IOException("文件名包含无效路径序列: " + originalFilename);
        }

        // 生成唯一文件名
        String fileExtension = "";
        if (originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String newFilename = UUID.randomUUID().toString() + fileExtension;

        // 保存文件
        Path uploadPath = Paths.get(uploadDir);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        try (InputStream inputStream = file.getInputStream()) {
            Path filePath = uploadPath.resolve(newFilename);
            Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);

            // 返回访问URL (相对路径)
            return accessPath + newFilename;
        }
    }

    // 删除头像文件的方法
    @Override
    public void deleteAvatar(String avatarUrl) {
        if (avatarUrl != null && avatarUrl.startsWith(accessPath)) {
            try {
                String filename = avatarUrl.substring(accessPath.length());
                Path filePath = Paths.get(uploadDir).resolve(filename);
                Files.deleteIfExists(filePath);
            } catch (IOException e) {
                // 记录错误但不向上抛出
                // 因为头像删除失败不应影响主流程
                System.err.println("删除头像失败: " + e.getMessage());
            }
        }
    }
}
